<?php
namespace app\modules\cn\models;

use app\modules\cn\models\Content;
use app\modules\content\models\Category as ContentCate;
use app\modules\exercise\models\ExerciseList as ExList;
use yii\db\ActiveRecord;
use yii;

class RankingAll extends ActiveRecord
{
    public $cateData;

    public static function tableName()
    {
        return '{{%ielts_test_result}}';
    }

    // 去空格 大转小写
    public static function getMytrim($str)
    {
        $search = array(" ", "　", "\n", "\r", "\t");
        $replace = array("", "", "", "", "");
        //  替换并大转小写
        $string = strtolower(str_replace($search, $replace, $str));
        //  strtoupper($string);
        return $string;
    }

    // 数字转字母 ---数组转换
    public static function getAlphnums($date)
    {
        foreach ($date as $k => $v) {
            $ch = 65;
            for ($i = 0; $i < 26; $i++) {
                if ($v == $i) {
                    // echo chr($ch+$i);
                    $res[$k] = chr($ch + $i);
                }
            }
        }
        return $res;
    }

    // 数字转字母 --单个 转换
    public static function getAlphnum($v)
    {
        $ch = 65;
        for ($i = 0; $i < 26; $i++) {
            if ($v == $i) {
                // echo chr($ch+$i);
                $res = chr($ch + $i);
            }
        }
        return $res;
    }

    // 数字转大写
    public static function getAlphnumup($v)
    {
        // daxie('0123456789');
        $da_num = array('一', '二', '三', '四', '五', '六', '七', '八', '九', '零');
        $leng = count($da_num);
        foreach ($da_num as $ky => $cal) {
            if ($ky == $v) {
                $res = $cal;
            }
        }
        return $res;
    }

    // 中英文分割   公用方法，传小组id---含3合一数组
    public static function getExplodesentence($pid)
    {
        $model = new Content();
        $array = $model->getClass(['fields' => 'description,answer,alternatives,article,listeningFile,duration,problemComplement,sencenter,giveup', 'where' => "c.pid=$pid"]);
        foreach ($array as $v) {
            $arrays[] = $v;
        }
        // print_r($arrays[0]['problemComplement']);
        // var_dump($arrays);die;
        $values = array();
        $sign = array();
        if (!empty($arrays)) {
            // 中英文分割合并
            foreach ($arrays as $value) {
                $dat = $value['problemComplement'];
                // var_dump($dat);
                if (!empty($dat)) {
                    $english = $model->getlabeldeletesetences($dat);
                    // print_r($english);die;
                } else {
                    $english = array();
                }
                if (!empty($dat)) {
                    $dats = $value['sencenter'];
                    $chinese = $model->getlabeldeletesetences($dats);
                } else {
                    $chinese = array();
                }
                if (!empty($dat)) {
                    $times = $value['duration'];

                    $times = explode("|", $times);
                    foreach ($times as $times) {
                        $time[] = explode(",", $times);
                    }
                } else {
                    $time = array();
                }

                if (!empty($time)) {
                    // var_dump($time);die;
                    $count = count($time[0]);
                    // var_dump($count);die;
                    if (!empty($time)) {
                        foreach ($time as $sy => $timer) {
                            foreach ($timer as $k => $v) {
                                if ($sy == 0) {
                                    $arr = array(isset($english[$k]) ? $english[$k] : NULL, isset($chinese[$k]) ? $chinese[$k] : NULL);
                                    $values[$sy]['listen'][] = $arr;
                                    $values[$sy]['time'][] = $timer[$k];
                                } else {
                                    $arr = array(isset($english[$k + $count]) ? $english[$k + $count] : NULL, isset($chinese[$k + $count]) ? $chinese[$k + $count] : NULL);
                                    $values[$sy]['listen'][] = $arr;
                                    $values[$sy]['time'][] = $timer[$k];
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
        //  var_dump($values);die;
        return $values;
    }

    //做题的数目
    public static function getUserAnswerNumber()
    {
        $userId = Yii::$app->session->get('userId');
        if ($userId) {
            $true = count(RankingAll::find()->where("userid =$userId AND result =1 and ISNULL(answer)=0 and LENGTH(trim(answer))>0")->asArray()->All()); //总正确数
            $questionData['total'] = $total = count(RankingAll::find()->where("userid = $userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0")->asArray()->All());  // 做题总数
            $startTime = strtotime(date('Y-m-d', time()));
            $questionData['todayTotal'] = $todayTotal = count(RankingAll::find()->where('userid =' . $userId . ' and createTime>' . $startTime . ' and ISNULL(answer)=0 and LENGTH(trim(answer))>0')->asArray()->All());//今日总数
            $todayTrue = count(RankingAll::find()->where('userid =' . $userId . ' and createTime>' . $startTime . ' and result=1 and ISNULL(answer)=0 and LENGTH(trim(answer))>0')->asArray()->All());//今日正确数
            $questionData['todayRatio'] = $todayTotal != false ? sprintf("%.2f", $todayTrue / $todayTotal) * 100 : '/';
            $questionData['totalRatio'] = $total != false ? sprintf("%.2f", $true / $total) * 100 : '/';
        } else {
            $questionData['totalRatio'] = $questionData['todayRatio'] = '/';
            $questionData['total'] = $questionData['todayTotal'] = 0;
        }
        return $questionData;
    }

    //每日任务目标
    public static function getAims($day=0)
    {
        $userId = Yii::$app->session->get('userId');
        if ($userId) {
            $yesterday = strtotime(date("Y-m-d", time() - $day * 24 * 3600));
            $today = strtotime(date("Y-m-d", time()));
            if ($day != false) {
                $where = "userid=$userId and createtime>=$yesterday and createtime<$today";
            } else {
                $where = "userid=$userId and createtime>$today";
            }
            $listen = count(RankingAll::find()->select('id')->where("$where and typeid=1")->all());//总数
            $read = count(RankingAll::find()->select('id')->where("$where and typeid=2")->all());
            $write = count(RankingAll::find()->select('id')->where("$where and typeid=3")->all());
            $userExpand = UserExpand::find()->asArray()->where("userId=$userId")->one();
            $userExpand['target'] =floatval($userExpand['target']);
            if ($userExpand['target'] < 6) {
                $aims['writeAims'] = 1;
                $aims['readAims'] = 2;
                $aims['listenAims'] = 2;
            } elseif ($userExpand['target'] == 6) {
                $aims['writeAims'] = 1;
                $aims['readAims'] = $read > 39 ? 3 : 5;
                $aims['listenAims'] = $listen > 30 ? 3 : 4;
            } elseif ($userExpand['target'] == 6.5) {
                $aims['writeAims'] = 2;
                $aims['readAims'] = $read > 65 ? 5 : 6;
                $aims['listenAims'] = $read > 40 ? 4 : 5;
            } elseif ($userExpand['target'] >= 7 ) {
                $aims['writeAims'] = 2;
                $aims['readAims'] = $read > 78 ? 6 : 7;
                $aims['listenAims'] = $read > 50 ? 5 : 6;
            } else{
                $aims['writeAims'] = 0;
                $aims['readAims'] = 0;
                $aims['listenAims'] = 0;
            }
            $aims['total'] = $aims['writeAims'] + $aims['readAims'] * 13 + $aims['listenAims'] * 10;//总题数
            $listen = $listen > ($aims['listenAims'] * 10) ? $aims['listenAims'] * 10 : $listen;//总数
            $read = $read > ($aims['readAims'] * 13) ? $aims['readAims'] * 13 : $read;
            $write = $write > $aims['writeAims'] ? $aims['writeAims'] : $write;
            $rate = round(($listen + $read + $write) / $aims['total'] * 100)>100?100:round(($listen + $read + $write) / $aims['total'] * 100);//完成比例
            $aims['rate'] = $rate > 100 ? 100 : $rate;

            //根据分数来判断做题数
        } else {
            $aims['listenAims'] = '-';
            $aims['readAims'] = '-';
            $aims['writeAims'] = '-';
            $aims['total'] = 0;
            $aims['rate'] = 0;
        }
        $aims = array_merge($aims, self::getUserFinished($day, $aims));
        return $aims;
    }

//每日任务目标
    public static function getUserFinished($day = 0, $aims)
    {
        $userId = Yii::$app->session->get('userId');
        $yesterday = strtotime(date("Y-m-d", time() - $day  * 24 * 3600));
        $today = strtotime(date("Y-m-d", time()));
        if ($userId) {
            if ($day != false) {
                $where = "userid=$userId and createtime>=$yesterday and createtime<$today";
            } else {
                $where = "userid=$userId and createtime>$today";
            }
            $finished['listenFinished'] = count(RankingAll::find()->select('id')->where("$where and typeid=1")->all());
            $finished['readFinished'] = count(RankingAll::find()->select('id')->where("$where and typeid=2")->all());
            $finished['writeFinished'] = count(RankingAll::find()->select('id')->where("$where and typeid=3")->all());
            $finished['writeStatus'] = self::getStatus($finished['writeFinished'],$aims['writeAims']);
            $finished['ReadStatus'] = self::getStatus($finished['readFinished'], $aims['readAims']);
            $finished['listenStatus'] = self::getStatus($finished['listenFinished'],$aims['listenAims']);
            $tem = RankingAll::find()->select('typeid')->where("$where and typeid!=4")->orderBy('id desc')->one();
            if($tem['typeid']==1){
                $finished['lastSubject']='听力';
            }elseif($tem['typeid']==2){
                $finished['lastSubject']='阅读';
            }else{
                $finished['lastSubject']='写作';
            }
            if($tem['typeid']==1){
                $finished['lastRate'] =  round($finished['listenFinished']/($aims['listenAims']*10)*100)>100?100:round($finished['listenFinished']/($aims['listenAims']*10)*100);
            } if($tem['typeid']==2){
                $finished['lastRate'] =  round($finished['readFinished']/($aims['readAims']*13)*100)>100?100:round($finished['readFinished']/($aims['readAims']*13)*100);
            }else{
                $finished['lastRate'] =  round($finished['writeFinished']/$aims['writeAims']*100)>100?100: round($finished['writeFinished']/$aims['writeAims']*100);
            }
            //根据分数来判断做题数
        } else {
            $finished['listenFinished'] = 0;
            $finished['readFinished'] = 0;
            $finished['writeFinished'] = 0;
            $finished['writeStatus'] = 0;
            $finished['ReadStatus'] = 0;
            $finished['listenStatus'] = 0;
            $finished['lastSubject'] = '-';
            $finished['lastRate'] = 0;
        }
        return $finished;
    }
    //完成状态
    public static function getStatus($finish,$aims)
    {
        if($finish==0){
            return 0;
        }else{
            if($finish<$aims){
                return 1;
            }else{
                return 2;
            }
        }
    }
    //默认的目标
    public static function getDefault()
    {
        $userId = Yii::$app->session->get('userId');
        $userExpand = UserExpand::find()->asArray()->where("userId=$userId")->one();
        if ($userExpand['target'] == 1) {
            $aims['writeAims'] = 1;
            $aims['readAims'] = 2;
            $aims['listenAims'] = 2;
        } elseif ($userExpand['target'] == 2) {
            $aims['writeAims'] = 1;
            $aims['readAims'] =  3;
            $aims['listenAims'] = 3;
        } elseif ($userExpand['target'] == 3) {
            $aims['writeAims'] = 2;
            $aims['readAims'] =  5 ;
            $aims['listenAims'] =  4 ;
        } elseif ($userExpand['target'] >= 4) {
            $aims['writeAims'] = 2;
            $aims['readAims'] = 6 ;
            $aims['listenAims'] =  5 ;
        } else{
            $aims['writeAims'] = 0;
            $aims['readAims'] = 0;
            $aims['listenAims'] = 0;
        }
        return $aims;
    }

    //获取错题分类
    public static function getWrongQuestion($data, $offset, $pageSize)
    {
        foreach ($data as $k => $v) {
//            $catName = ContentCate::find()->asArray()->where('id=' . $v['catId'])->one();
            $catName = ExList::find()->asArray()->where('cate_id=' . $v['catId'])->one();
            if ($v['typeid'] == 1) {
                $name1 = '听力';
//                if ($catName['pid'] != 413) {
//                    unset($data[$k]);
//                    continue;
//                }
            } elseif ($v['typeid'] == 2) {
                $name1 = '阅读';
            } elseif ($v['typeid'] == 3) {
                $name1 = '写作';
            } elseif ($v['typeid'] == 4) {
                $name1 = '口语';
            }
            if (strpos($v['name'], '剑雅') === false) {
                $data[$k]['catName'] = $name1 . '-' . $catName['catName'] . '-' . str_replace(' - ', '-', $v['name']);
            } else {
                $data[$k]['catName'] = $name1 . '-' . str_replace(' - ', '-', $v['name']);
            }
        }
        $question = array_slice($data, $offset, $pageSize);
        return $question;
    }

    public static function getCategory()
    {
        $category[0]=ContentCate::find()->asArray()->where('pid=413')->all();//听力
        $category[1]=ContentCate::find()->asArray()->where('pid=462')->all();//阅读
        $category[2]=ContentCate::find()->asArray()->where('pid=512')->all();
        $category[3]=ContentCate::find()->asArray()->where('pid=537')->all();
        return $category;
    }

    //累计
    public static function getQuestionCount()
    {
        $userId = Yii::$app->session->get('userId');
        $question['listen']=RankingAll::find()->asArray()->where('userid='.$userId.' and typeid=1')->count();
        $question['read']=RankingAll::find()->asArray()->where('userid='.$userId.' and typeid=2')->count();
        $question['write']=RankingAll::find()->asArray()->where('userid='.$userId.' and typeid=3')->count();
        $question['spoken']=RankingAll::find()->asArray()->where('userid='.$userId.' and typeid=4')->count();
        return $question;
    }
    //一周以来每天的做题正确百分比
    public static function getQuestionRate($time='')
    {
        $userId = Yii::$app->session->get('userId');
        if ($time == false) {
            $date = date('w');//星期几
            if ($date > 1) {
                $startTime = strtotime('last monday');//星期1
            } elseif ($date = 1) {
                $startTime = strtotime(date('Y-m-d'), time());
            } else {
                $startTime = strtotime('next week monday');//星期1
            }
        } else {
            $startTime = $time;
        }
        $data=array();
        for($i=0;$i<7;$i++){
            $start=$startTime+$i*24*3600;
            $end=$startTime+($i+1)*24*3600;
//            var_dump(date('Y-m-d',$start));var_dump('||');
//            var_dump(date('Y-m-d',$end));//周一的时候看一下周一的情况
            $listen=RankingAll::find()->asArray()->select('count(id) as count')->where('userid='.$userId.' and createtime>'.$start.' and  createtime<'.$end.' and typeid=1')->one()['count'];
            $listenCorrect=RankingAll::find()->asArray()->select('count(id)  as count')->where('userid='.$userId.' and createtime>'.$start.' and  createtime<'.$end.' and typeid=1 and result=1')->one()['count'];
            $read=RankingAll::find()->asArray()->select('count(id)  as count')->where('userid='.$userId.' and createtime>'.$start.' and  createtime<'.$end.' and typeid=2')->one()['count'];
            $readCorrect=RankingAll::find()->select('count(id)  as count')->asArray()->where('userid='.$userId.' and createtime>'.$start.' and  createtime<'.$end.' and typeid=2 and result=1')->one()['count'];
            $data[$i]['all']=round(($listenCorrect+$readCorrect)/($listen+$read)*100);
            $data[$i]['listen']=round($listenCorrect/$listen*100);
            $data[$i]['read']=round($readCorrect/$read*100);
        }

        return $data;
    }

    /**
     * @Title  [雅思做题得分]
     * @Author Don
     * @Date   2021-05-06
     * @return [type]
     */
    public static function score($rate)
    {  
        $score = 0;
        if ($rate >= 0 && $rate < 5) {
            $score = 0;
        } elseif ($rate >= 5 && $rate < 15) {
            $score = 1;
        } elseif ($rate >= 15 && $rate < 20) {
            $score = 1.5;
        } elseif ($rate >= 20 && $rate < 25) {
            $score = 2;
        } elseif ($rate >= 25 && $rate < 30) {
            $score = 2.5;
        } elseif ($rate >= 30 && $rate < 35) {
            $score = 3;
        } elseif ($rate >= 35 && $rate < 40) {
            $score = 3.5;
        } elseif ($rate >= 40 && $rate < 45) {
            $score = 4;
        } elseif ($rate >= 45 && $rate < 50) {
            $score = 4.5;
        } elseif ($rate >= 50 && $rate < 60) {
            $score = 5;
        } elseif ($rate >= 60 && $rate < 65) {
            $score = 5.5;
        } elseif ($rate >= 65 && $rate < 70) {
            $score = 6;
        } elseif ($rate >= 70 && $rate < 75) {
            $score = 6.5;
        } elseif ($rate >= 75 && $rate < 80) {
            $score = 7;
        } elseif ($rate >= 80 && $rate < 85) {
            $score = 7.5;
        } elseif ($rate >= 85 && $rate < 90) {
            $score = 8;
        } elseif ($rate >= 90 && $rate < 100) {
            $score = 8.5;
        } else {
            $score = 9;
        }
        
        return $score;
    }

    /**
     * @Title  [分数格式化]
     * @Author Don
     * @Date   2021-05-10
     * @param  [type]
     * @return [type]
     */
    public static function formatScore($score)
    {
        $score_explode = explode('.', $score);
        $result = 0;
        if (isset($score_explode[1])) {
            $xiaoshu = $score - $score_explode[0];
            if ($xiaoshu == 0.5) {
                $result = $score;
            } else {
                $result = round($score);
            }
        } else {
            $result = $score;
        }

        return $result;
    }

    // 总  --听 说读写  排行榜
    //by:sjeam
    public function getlistentestorder($typeid)
    {
        $userId = \Yii::$app->session->get('userId');
        if ($typeid == 0) {
            // 改变 总榜排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 1) {
            // 改变 听总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 2) {
            // 改变 说总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 3) {
            // 改变 读总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        } else if ($typeid == 4) {
            // 改变 写总排名
            $false = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 0])->distinct()->asArray()->All());
            $allnum = count(RankingAll::find()->where(['userid' => $userId, 'typeid' => $typeid, 'result' => 1])->distinct()->asArray()->All());
            $totals = $false + $allnum;
            $percentage = number_format(($allnum / $totals), 2) * 100;
        }
        // 取testid  降维
        $testorder = RankingOrder::find()->where(['userid' => $userId, 'typeid' => $typeid])->distinct()->asArray()->All();

        if (!empty($testorder)) {
            $id = $testorder[0]['id'];
            \Yii::$app->db->createCommand()->update('{{%ielts_test_order}}', [
                'order' => $percentage,
            ], 'id=' . $id)->execute();
        } else {
            \Yii::$app->db->createCommand()->insert('{{%ielts_test_order}}', [
                'userid' => $userId,
                'typeid' => $typeid,
                'order' => $percentage
            ])->execute();
        }
        return true;
    }

}